<?php

namespace Common\Utils;
//判断是否有定义INC，没有则直接退出 要调用PHPExcelUtils必须定义INC
//if(!defined("INC")){
//    exit('Access Denied');
//}
class PHPExcelUtils
{
    public function read($filename, $encode = 'utf-8')
    {
        vendor('PHPExcel');
        vendor('PHPExcel.PHPExcel_IOFactory');
        vendor('PHPExcel.PHPExcel_Cell');
        setlocale(LC_ALL, 'zh_CN');
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');//读取xls
        if (!$objReader->canRead($filename)) {
            //读取xlsx
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            if (!$objReader->canRead($filename)) {
                return false;
            }
        }
//        $objReader->setInputEncoding('GBK');
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $value = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
               if($col == 8){//指定H列为时间所在列
                    $value = gmdate("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($value));
               }
        //        $cell =$objWorksheet->getCellByColumnAndRow($col, $row);
        //        if($cell->getDataType()==\PHPExcel_Cell_DataType::TYPE_NUMERIC){
        //            $value = gmdate("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($value));
        //        }
                $value = iconv('utf-8', 'gb2312', $value);//解决中文乱码
                $excelData[$row][] = $value;
            }
        }
        return $excelData;
    }


    public function setCellList($cellList){

        vendor('PHPExcel');
        $obj = new \PHPExcel();
        $obj->setActiveSheetIndex(0);
        $objSheet = $obj->getActiveSheet();
        $len = count($cellList);
        $start = ord('A');
        for($i = 0; $i < $len; $i++)
        {
            $objSheet->setCellValue(chr($start).'1', $cellList[$i]);
            $start++;
        }

        return $obj;

    }

}